/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
////////////definde regex//////////
var ZPROFILE_USERNAME_PATTERN = /^[a-zA-Z_-_.]{3,20}$/;
var ZPROFILE_PASSWORD_PATTERN = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{6,}$/;
var ZPROFILE_DISPLAY_NAME_PATTERN = /^.{0,50}$/;
var ZPROFILE_EMAIL_PATTERN = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var ZPROFILE_MOBILE_PATTERN = /^(?:0084|\+84|0)[0-9]{9,10}$/;
/////// end define regex //////////
var ZPROFILE_INVALID_USERNAME_MESSAGE = "Only characters A-Z, a-z , ' - ' and '.' and between 3 and 20 characters.";
var ZPROFILE_INVALID_PASSWORD_MESSAGE = "Must contain at least one digit, at least one lower case, at least one upper case and at least 6 characters.";
var ZPROFILE_INVALID_CONFIRM_PASSWORD_MESSAGE = "Confirm password not match.";
var ZPROFILE_INVALID_DATEOFBIRTH_MESSAGE = "Date of birth not valid.";
var ZPROFILE_INVALID_EMAIL_MESSAGE = "Email address not valid.";
var ZPROFILE_INVALID_MOBILENUMBER_MESSAGE = "Mobile number not valid.";
var ZPROFILE_INVALID_DISPLAYNAME_MESSAGE = "Display name not valid.The max lengnth is 50 characters.";
var ZPROFILE_INVALID_GENDER_MESSAGE = "Gender not valid.";
var ZPROFILE_EMPTY_USERNAME_MESSAGE = "Username cannot be empty.";
var ZPROFILE_NOTSAME_PASSWORD_MESSAGE = "Current password and new password must not be same.";
var ZPROFILE_NOTMACH_PASSWORD_MESSAGE = "Confirm password not match.";
var ZPROFILE_EMPTY_PASSWORD_MESSAGE = "Password cannot be empty.";


window.addEventListener('load', function() {
    // Executes when the window has completed loading
    var backs = document.getElementsByClassName('backBtn');
    for (var i = 0; i < backs.length; i++) {
        var element = backs[i];
        if (element.addEventListener) {
            element.addEventListener('click', goBack, false);
        } else if (element.attachEvent) {
            element.attachEvent('onclick', goBack);
        }
    }

}, false);


function bindEvent(element, event, callback) {
    if (element.addEventListener) {
        element.addEventListener(event, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent('on' + event, callback);
    }
}


function goBack() {
    window.history.back();
}


//////// create profile///////////

function validateProfileOnKeyUp(element) {
    //var element = event.target;
    removeError2(element);
    if (element.id === 'username' && !ZPROFILE_USERNAME_PATTERN.test(element.value)) {
        addError(element, ZPROFILE_INVALID_USERNAME_MESSAGE);
    }
    if (element.id === 'password' && !ZPROFILE_PASSWORD_PATTERN.test(element.value)) {
        addError(element, ZPROFILE_INVALID_PASSWORD_MESSAGE);
    }
    var compareNode = document.getElementById('newPassword');
    if (null === compareNode || undefined === compareNode) {
        compareNode = document.getElementById('password');
    }


    if (element.id === 'confirmPassword' && compareNode.value !== element.value) {
        addError(element, ZPROFILE_INVALID_CONFIRM_PASSWORD_MESSAGE);
    }
    if (element.id === 'displayName' && !ZPROFILE_DISPLAY_NAME_PATTERN.test(element.value)) {
        addError(element, ZPROFILE_INVALID_DISPLAYNAME_MESSAGE);
    }

    if (element.id === 'email' && element.value.length > 0 && !ZPROFILE_EMAIL_PATTERN.test(element.value)) {
        addError(element, ZPROFILE_INVALID_EMAIL_MESSAGE);
    }
    if (element.id === 'mobile' && element.value.length > 0 && !ZPROFILE_MOBILE_PATTERN.test(element.value)) {
        addError(element, ZPROFILE_INVALID_MOBILENUMBER_MESSAGE);
    }

    if (element.id === 'currentPassword' && !ZPROFILE_PASSWORD_PATTERN.test(element.value)) {
        addError(element, ZPROFILE_INVALID_PASSWORD_MESSAGE);
    }
    if (element.id === 'newPassword' && !ZPROFILE_PASSWORD_PATTERN.test(element.value)) {
        addError(element, ZPROFILE_INVALID_PASSWORD_MESSAGE);
    }

    if (element.id === 'newPassword' && ZPROFILE_PASSWORD_PATTERN.test(element.value) && document.getElementById('currentPassword').value === element.value) {
        addError(element, ZPROFILE_NOTSAME_PASSWORD_MESSAGE);
    }
}
function validateProfileField(name, value) {

    if (name === 'displayName' && !ZPROFILE_DISPLAY_NAME_PATTERN.test(value)) {
        error(ZPROFILE_INVALID_DISPLAYNAME_MESSAGE);
        return false;
    }
    if (name === 'email' && value.length > 0 && !ZPROFILE_EMAIL_PATTERN.test(value)) {
        error(ZPROFILE_INVALID_EMAIL_MESSAGE);
        return false;
    }
    if (name === 'mobile' && value.length > 0 && !ZPROFILE_MOBILE_PATTERN.test(value)) {
        error(ZPROFILE_INVALID_MOBILENUMBER_MESSAGE);
        return false;
    }
    return true;
}
function createProfile() {
    removeError();
    var username = document.getElementById('username');
    var password = document.getElementById('password');
    var confirmPassword = document.getElementById('confirmPassword');
    var gender = document.getElementById('gender');
    var mobile = document.getElementById('mobile');
    var displayName = document.getElementById('displayName');
    var email = document.getElementById('email');
    var cityId = document.getElementById('cityId');
    var date = document.getElementById('dateOfBirth');
    var dateOfBirth = dateToInt(date.value);


    if (!validateProfile(username, password, confirmPassword, gender, mobile, displayName, email, cityId, date))
        return;

    var profile = {};
    profile.username = username.value;
    profile.password = password.value;
    profile.displayName = displayName.value;
    profile.email = email.value;
    profile.cityId = cityId.value;
    profile.dateOfBirth = dateOfBirth;
    profile.mobile = mobile.value;
    profile.gender = gender.value;
    console.log(profile);
    ajaxPostCreateProfile(profile);
}

function validateProfile(username, password, confirmPassword, gender, mobile, displayName, email, cityId, date) {
    var flag = true;
    var dateOfBirth = dateToInt(date.value);
    if (!validateDate(date.value)) {
        addError(date, ZPROFILE_INVALID_DATEOFBIRTH_MESSAGE);
        flag = false;
    }
    if (!ZPROFILE_USERNAME_PATTERN.test(username.value)) {
        addError(username, ZPROFILE_INVALID_USERNAME_MESSAGE);
        flag = false;
    }
    if (!ZPROFILE_PASSWORD_PATTERN.test(password.value)) {
        addError(password, ZPROFILE_INVALID_PASSWORD_MESSAGE);
        flag = false;
    }
    if (confirmPassword.value !== password.value) {
        addError(confirmPassword, ZPROFILE_INVALID_CONFIRM_PASSWORD_MESSAGE);
        flag = false;
    }
    if (!ZPROFILE_DISPLAY_NAME_PATTERN.test(displayName.value)) {
        addError(displayName, ZPROFILE_INVALID_DISPLAYNAME_MESSAGE);
        flag = false;
    }
    var now = parseInt((new Date().getTime() / 1000));
    if (now - dateOfBirth < 3600 * 24 * 365 * 10 || now - dateOfBirth > 3600 * 24 * 365 * 100) {
        console.log(now + "-" + dateOfBirth + "=" + (now - dateOfBirth));
        addError(date, "You're too young or old.");
        flag = false;
    }
    if ("" === date.value || null === dateOfBirth || undefined === dateOfBirth || NaN === dateOfBirth) {
        addError(date, ZPROFILE_INVALID_DATEOFBIRTH_MESSAGE);
        flag = false;
    }
    if (null === gender.value || undefined === gender.value || NaN === gender.value) {
        addError(gender, ZPROFILE_INVALID_GENDER_MESSAGE);
        flag = false;
    }
    if (email.value.length > 0 && !ZPROFILE_EMAIL_PATTERN.test(email.value)) {
        addError(email, ZPROFILE_INVALID_EMAIL_MESSAGE);
        flag = false;
    }
    if (mobile.value.length > 0 && !ZPROFILE_MOBILE_PATTERN.test(mobile.value)) {
        addError(mobile, ZPROFILE_INVALID_MOBILENUMBER_MESSAGE);
        flag = false;
    }
    return flag;
}

function ajaxPostCreateProfile(profile)
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
        {
            var result = JSON.parse(xmlhttp.responseText);
            if (result.STATUS === 'SUCCESS') {
                window.location.href = result.MESSAGE;
            }
            else {
                addError2(result.MESSAGE);
            }
        }
    };
    //xmlhttp.setRequestHeader("Content-Type", "application/son;charset=UTF-8");

    xmlhttp.open("POST", "/ajaxCreate", true);
    xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
    xmlhttp.send("profile=" + encodeURIComponent(JSON.stringify(profile)));
}

/////// end create profile ///////

/////// log in////////////////

function logIn() {
    removeError();
    var username = document.getElementById('username');
    var password = document.getElementById('password');
    var isRemember = document.getElementById("isRemember").checked;

    if (!validateLogIn(username, password))
        return;
    if (undefined === isRemember || "" === isRemember || null === isRemember)
        isRemember = true;
    console.log(username.value + ":" + password.value + isRemember);
    ajaxPostLogIn(username.value, password.value, isRemember);
}

function validateLogIn(username, password) {
    var flag = true;
    if (undefined === username.value || "" === username.value || null === username.value) {
        addError(username, ZPROFILE_EMPTY_USERNAME_MESSAGE);
        flag = false;
    }
    if (undefined === password.value || "" === password.value || null === password.value) {
        addError(password, ZPROFILE_EMPTY_PASSWORD_MESSAGE);
        flag = false;
    }
    return flag;

}

function ajaxPostLogIn(username, password, isRemember) {

    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
        {
            var result = JSON.parse(xmlhttp.responseText);
            if (result.STATUS === 'SUCCESS') {
                window.location.href = result.MESSAGE;
            }
            else {
                addError2(result.MESSAGE);
            }
        }
    };
    //xmlhttp.setRequestHeader("Content-Type", "application/son;charset=UTF-8");

    xmlhttp.open("POST", "/ajaxLogin", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("username=" + username + "&password=" + password + "&isRemember=" + isRemember);

}
//////// end log in/////////////////


/////////change password ////////////
function changePassword() {
    removeError();
    var currentPassword = document.getElementById('currentPassword');
    var newPassword = document.getElementById('newPassword');
    var confirmPassword = document.getElementById('confirmPassword');
    if (!validateChangePassword(currentPassword, newPassword, confirmPassword))
        return;
    ajaxPostChangePassword(currentPassword, newPassword, confirmPassword);
}

function validateChangePassword(password, newPassword, confirmPassword) {
    var flag = true;
    if (!ZPROFILE_PASSWORD_PATTERN.test(password.value)) {
        addError(password, ZPROFILE_INVALID_PASSWORD_MESSAGE);
        flag = false;
    }
    if (!ZPROFILE_PASSWORD_PATTERN.test(newPassword.value)) {
        addError(newPassword, ZPROFILE_INVALID_PASSWORD_MESSAGE);
        flag = false;
    }

    if (ZPROFILE_PASSWORD_PATTERN.test(password.value) && password.value === newPassword.value) {
        addError(newPassword, ZPROFILE_NOTSAME_PASSWORD_MESSAGE);
        flag = false;
    }

    if (confirmPassword.value !== newPassword.value) {
        addError(confirmPassword, ZPROFILE_NOTMACH_PASSWORD_MESSAGE);
        flag = false;
    }



    return flag;
}

function ajaxPostChangePassword(currentPassword, newPassword, confirmPassword) {
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
        {
            var result = JSON.parse(xmlhttp.responseText);
            if (result.STATUS === 'SUCCESS') {
                addInfo(result.MESSAGE);
                currentPassword.value = '';
                newPassword.value = '';
                confirmPassword.value = '';
            }
            else {
                addError2(result.MESSAGE);
            }
        }
    };
    //xmlhttp.setRequestHeader("Content-Type", "application/son;charset=UTF-8");

    xmlhttp.open("POST", "/ajaxChangePassword", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("currentPassword=" + currentPassword.value + "&newPassword=" + newPassword.value);
}

/////////end change password /////////


/////// update profile////////////
function updateProfile() {
    removeError();
    var gender = document.getElementById('gender');
    var mobile = document.getElementById('mobile');
    var displayName = document.getElementById('displayName');
    var email = document.getElementById('email');
    var cityId = document.getElementById('cityId');
    var date = document.getElementById('dateOfBirth');
    var dateOfBirth = dateToInt(date.value);

    if (!validateUpdateProfile(gender, mobile, displayName, email, cityId, date))
        return;

    var profile = {};
    profile.displayName = displayName.value;
    profile.email = email.value;
    profile.cityId = cityId.value;
    profile.dateOfBirth = dateOfBirth;
    profile.mobile = mobile.value;
    profile.gender = gender.value;
    console.log(profile);
    ajaxPostUpdateProfile(profile);
}
function validateUpdateProfile(gender, mobile, displayName, email, cityId, date) {
    var flag = true;
    var dateOfBirth = dateToInt(date.value);
    if (!validateDate(date.value)) {
        addError(date, ZPROFILE_INVALID_DATEOFBIRTH_MESSAGE);
        flag = false;
    }
    if (!ZPROFILE_DISPLAY_NAME_PATTERN.test(displayName.value)) {
        addError(displayName, ZPROFILE_INVALID_DISPLAYNAME_MESSAGE);
        flag = false;
    }
    if ("" === date.value || null === dateOfBirth || undefined === dateOfBirth || NaN === dateOfBirth) {
        addError(date, ZPROFILE_INVALID_DATEOFBIRTH_MESSAGE);
        flag = false;
    }
    if (null === gender.value || undefined === gender.value || NaN === gender.value) {
        addError(gender, ZPROFILE_INVALID_GENDER_MESSAGE);
        flag = false;
    }
    if (email.value.length > 0 && !ZPROFILE_EMAIL_PATTERN.test(email.value)) {
        addError(email, ZPROFILE_INVALID_EMAIL_MESSAGE);
        flag = false;
    }
    if (mobile.value.length > 0 && !ZPROFILE_MOBILE_PATTERN.test(mobile.value)) {
        addError(mobile, ZPROFILE_INVALID_MOBILENUMBER_MESSAGE);
        flag = false;
    }
    return flag;
}

function ajaxPostUpdateProfile(profile) {
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
        {
            var result = JSON.parse(xmlhttp.responseText);
            if (result.STATUS === 'SUCCESS') {
                window.location.href = result.MESSAGE;
            }
            else {
                addError2(result.MESSAGE);
            }
        }
    };
    //xmlhttp.setRequestHeader("Content-Type", "application/son;charset=UTF-8");

    xmlhttp.open("POST", "/ajaxUpdate", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("profile=" + encodeURIComponent(JSON.stringify(profile)));

}


//////// end update profile ////////

///////// change status////////////

function changeStatus(element) {
    popup('Are you sure you want to change status this profile?', ajaxChangeStatus, element);
}


function ajaxChangeStatus(element) {
    popUpCancel();
    console.log(element);
    var params = element.getAttribute("params");
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
        {
            var result = JSON.parse(xmlhttp.responseText);
            if (result.STATUS === 'SUCCESS') {
                info(result.MESSAGE);
            }
            else {
                info(result.MESSAGE);
            }
        }

    };
    //xmlhttp.setRequestHeader("Content-Type", "application/son;charset=UTF-8");

    xmlhttp.open("POST", "/ajaxChangesStatus", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(params);
}

////////end change status//////////////


/////////// profile pagging //////////////

//function managePageNumbers(pageContainer, pageNum)
//{
//    var currPage = pageContainer.attr("curr");
//    var pgCount = pageContainer.attr("count");
//    var cnt = 0;
//    var temp = "";
//    for (var i = currPage - 5; i <= currPage + 10; i++)
//    {
//        if (cnt === 10 || i > pgCount)
//            break;
//        if (i >= 1 && i <= pgCount) {
//            if (i === parseInt(pageNum)) {
//                temp += " <a href='javascript:void(0);' class='active'>" + i + "</a> ";
//            }
//            else {
//                temp += " <a href='javascript:void(0);'>" + i + "</a> ";
//            }
//            cnt++;
//        }
//    }
//}

function managePageNumbers()
{
    var obj = document.getElementById("pageNumbers");
    obj.innerHTML = "";
    var cnt = 0;
    for (i = currPage - 5; i <= currPage + 10; i++)
    {
        if (cnt === 10)
            break;
        if (i >= 1 && i <= pgCount) {
            obj.innerHTML += " <a class='profileList' href='javascript:void(0);' onclick='showPage(" + i + ")'>" + i + "</a> ";
            cnt++;
        }
    }

    var listNode = document.getElementById('pageNumbers').getElementsByTagName("a");
    for (var i = 0; i < listNode.length; i++) {
        if (parseInt(listNode[i].innerHTML) === currPage) {
            listNode[i].setAttribute("style", "background-color: #0D477D !important;color:white!important;");
            break;
        }
    }

}

function showPage(pageNum) {
    ///////////
    if (currPage === pageNum)
        return;
    ajaxProfilePaging(pageNum);
    ///////////
    currPage = pageNum;
    managePageNumbers(pageNum);
}

function ajaxProfilePaging(pageNum) {
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
        {
            var result = xmlhttp.responseText;
            var table = document.getElementById("profileList");
            if (undefined !== result && "" !== result && null !== result) {
                table.innerHTML = result;
            } else {
                addError(table, "There are some error.");
            }
        }

    };
    //xmlhttp.setRequestHeader("Content-Type", "application/son;charset=UTF-8");

    xmlhttp.open("POST", "/list", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("page=" + pageNum);
}

/////////// end profile pagging //////////////
